package com.main.sales.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.main.sales.common.CustomException;
import com.main.sales.mapper.CategoryMapper;
import com.main.sales.pojo.Category;
import com.main.sales.pojo.Dish;
import com.main.sales.pojo.Setmeal;
import com.main.sales.service.CategoryService;
import com.main.sales.service.DishService;
import com.main.sales.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    /**
     * 根据id删除分类，删除之前需要进行判断
     *
     * @param id
     */
    @Override
    public void remove(Long id) {
        //添加查询条件，根据id分类 进行查询
        LambdaQueryWrapper<Dish> dishLQW = new LambdaQueryWrapper<>();
        dishLQW.eq(Dish::getCategoryId, id);
        long count1 = dishService.count(dishLQW);

        //1.查询当前分类是否关联菜品，如果已经关联，抛出出一个业务异常
        if (count1 > 0) {
            //1.1已经关联菜品，抛出与一个一业务异常
            throw new CustomException("当前分类下关联了菜品，不能删除");
        }

        //2.查询当前分类是否关联套餐，如果已经关联，抛出出一个业务异常
        LambdaQueryWrapper<Setmeal> setmealLQW = new LambdaQueryWrapper<>();
        setmealLQW.eq(Setmeal::getCategoryId, id);
        long count2 = setmealService.count(setmealLQW);
        if (count2 > 0) {
            //2.1已经关联套餐，抛出与一个一业务异常
            throw new CustomException("当前分类下关联了套餐，不能删除");
        }

        //3.正常删除分类
        super.removeById(id);
    }
}
